<template>
  <div class="container" :class="{ fullscreen: isFullscreen }">
    <!-- 全国地图 机构趋势模块 -->
    <div class="china">
      <div id="chinaMap" v-show="currentLevel === 'country'"></div>
      <div id="provinceMap" v-if="currentLevel === 'province'">
        <div v-if="loadingProvince">加载中...</div>
      </div>
    </div>
    <div class="full-screen" @click="toggleFullscreen">
      <svg-icon
        :icon-class="isFullscreen ? 'exit-fullscreen' : 'fullscreen'"
        class="fullscreen-icon"
      ></svg-icon>
    </div>
    <!-- 点击返回全国-->
    <div
      v-show="currentLevel === 'province'"
      @click="returnToChina"
      class="return-button"
    >
      ← 返回全国地图
    </div>
    <div class="statistics-wrapper">
      <h3>项目统计</h3>
      <p>项目总数:<span>2031</span></p>
      <p>设备总数:<span>18873</span></p>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import {
  code,
  totalMap,
  provinceNameMap,
  provinceGeoData,
} from "@/views/MapModule/data/mapConfig";

export default {
  name: "ChinaMap",
  props: {
    value: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      codeData: code,
      currentLevel: "country",
      loadingProvince: false,
      totalMapData: totalMap,
      provinceNameMap: provinceNameMap,
      provinceGeoData: provinceGeoData,
      isFullscreen: false,
      chinaChart: null,
      provinceChart: null,
    };
  },

  watch: {
    value() {
      this.initChar();
    },
    currentLevel: {
      handler(newVal, oldVal) {
        if (oldVal) {
          setTimeout(() => {
            this.resizeCharts();
          }, 50);
        }
      },
      immediate: true,
    },
  },

  mounted() {
    this.initChar();
    document.addEventListener("keydown", this.handleEscKey);
    // 监听全屏变化事件
    document.addEventListener("fullscreenchange", this.handleFullscreenChange);
    document.addEventListener("webkitfullscreenchange", this.handleFullscreenChange);
    document.addEventListener("mozfullscreenchange", this.handleFullscreenChange);
    document.addEventListener("MSFullscreenChange", this.handleFullscreenChange);
    // 监听窗口大小变化
    window.addEventListener("resize", this.handleWindowResize);
  },
  beforeDestroy() {
    // 移除事件监听器
    document.removeEventListener("keydown", this.handleEscKey);
    document.removeEventListener("fullscreenchange", this.handleFullscreenChange);
    document.removeEventListener("webkitfullscreenchange", this.handleFullscreenChange);
    document.removeEventListener("mozfullscreenchange", this.handleFullscreenChange);
    document.removeEventListener("MSFullscreenChange", this.handleFullscreenChange);
    window.removeEventListener("resize", this.handleWindowResize);

    // 销毁图表实例
    if (this.chinaChart) {
      this.chinaChart.dispose();
    }
    if (this.provinceChart) {
      this.provinceChart.dispose();
    }
  },
  methods: {
    handleProvinceClick(provinceName) {
      // 设置当前层级为省份级别;
      this.currentLevel = "province";
      // 显示加载状态
      this.loadingProvince = true;

      // 使用nextTick确保DOM更新后再加载省份地图
      this.$nextTick(() => {
        // 加载省份地图数据
        this.loadProvinceMap(provinceName);
      });
    },

    loadProvinceMap(provinceName) {
      // 查找省份的真实名称（处理简称到全称的映射）
      let realProvinceName = provinceName;
      // 检查是否需要映射
      for (let [shortName, fullName] of Object.entries(this.provinceNameMap)) {
        if (shortName === provinceName || fullName === provinceName) {
          realProvinceName = fullName;
          break;
        }
      }

      // 初始化省份地图容器
      this.$nextTick(() => {
        // 如果省份图表实例已存在，先销毁
        if (this.provinceChart) {
          this.provinceChart.dispose();
        }

        const provinceMapElement = document.querySelector("#provinceMap");
        if (provinceMapElement) {
          this.provinceChart = echarts.init(provinceMapElement);

          // 关键：检查并注册省份地图数据
          if (this.provinceGeoData && this.provinceGeoData[realProvinceName]) {
            // 去除 Vue 的响应式包装
            const geoData = JSON.parse(
              JSON.stringify(this.provinceGeoData[realProvinceName])
            );
            echarts.registerMap(realProvinceName, geoData);
          } else {
            console.warn(`未找到${realProvinceName}的GeoJSON数据`);
            this.loadingProvince = false;
            return;
          }

          // 配置选项
          const option = {
            title: {
              text: `${realProvinceName}电采暖设备分布`,
              left: "center",
              textStyle: {
                color: "#ffffff",
                fontSize: 24,
              },
            },
            tooltip: {
              trigger: "item",
              showDelay: 0,
              transitionDuration: 0.2,
              borderColor: "rgba(255, 255, 255, 0.2)",
              backgroundColor: "rgba(0, 0, 0, 0.8)",
              borderWidth: 1,
              textStyle: {
                color: "#ffffff",
              },
              formatter: (params) => {
                return `${params.name}: ${params.value || 0}%`;
              },
            },
            visualMap: {
              min: 0,
              max: 150,
              left: "30px",
              bottom: "20px",
              text: ["高", "低"],
              calculable: true,
              inRange: {
                color: ["#133a73", "#143a73", "#123a73"],
              },
              textStyle: {
                color: "#ffffff",
              },
            },

            series: [
              {
                name: "完成率",
                type: "map",
                map: realProvinceName,
                roam: false,
                label: {
                  show: true,
                  fontSize: 12,
                  color: "#fff",
                },
                itemStyle: {
                  areaColor: "#031f41",
                  borderWidth: 2,
                  borderColor: "#2c6097",
                },
                emphasis: {
                  label: {
                    show: true,
                    color: "#ffffff",
                    fontSize: 14,
                  },
                  itemStyle: {
                    areaColor: "#1e90ff",
                    borderColor: "#8ab4e5",
                    borderWidth: 2,
                  },
                },
                select: {
                  label: {
                    show: true,
                    color: "#ffffff",
                    fontSize: 14,
                  },
                  itemStyle: {
                    areaColor: "#143a73",
                    borderColor: "#2c6097",
                    borderWidth: 2,
                  },
                },
                selectedMode: "single", // 启用选中模式
                data: [], // 空数据数组
              },
            ],
          };

          // 使用setTimeout确保在下一个事件循环中设置选项
          setTimeout(() => {
            if (this.provinceChart) {
              this.provinceChart.setOption(option, true);
              this.loadingProvince = false;

              // 确保图表正确显示
              this.$nextTick(() => {
                setTimeout(() => {
                  if (this.provinceChart) {
                    this.provinceChart.resize();
                  }
                }, 50);
              });
            }
          }, 0);
        }
      });
    },

    initChar() {
      // 基于准备好的dom，初始化echarts实例
      const chinaMapElement = document.querySelector("#chinaMap");
      if (chinaMapElement) {
        // 如果全国图表实例已存在，先销毁
        if (this.chinaChart) {
          this.chinaChart.dispose();
        }

        this.chinaChart = echarts.init(chinaMapElement);

        // // 检查必要的数据是否存在
        if (
          !this.codeData ||
          !this.codeData[this.value] ||
          !this.codeData[this.value].mapData
        ) {
          console.error("地图数据未正确加载");
          return;
        }

        echarts.registerMap(
          this.codeData[this.value].word,
          this.codeData[this.value].mapData
        );
        // 显示南海诸岛迷你地图使用这个注册方式
        // echarts.registerMap("china", this.codeData[this.value].mapData);

        // 转换数据，确保名称匹配，添加安全检查
        const mapData = [];
        if (this.totalMapData && Array.isArray(this.totalMapData)) {
          for (const item of this.totalMapData) {
            if (item) {
              mapData.push({
                name:
                  (this.provinceNameMap && this.provinceNameMap[item.comname2]) ||
                  item.comname2,
                value: item.achieveRate,
                preium: item.preium,
                target: item.target,
              });
            }
          }
        }

        // 准备有数据省份的标记点数据
        const provincesWithStars = [];
        // 准备航线数据（从北京出发到各省份）
        const beijingCoord = [116.405285, 39.904989]; // 北京坐标
        const linesData = [];

        // 遍历所有有数据的省份
        if (this.totalMapData && Array.isArray(this.totalMapData)) {
          for (const item of this.totalMapData) {
            if (item) {
              const provinceName =
                (this.provinceNameMap && this.provinceNameMap[item.comname2]) ||
                item.comname2;
              // 获取省份中心点坐标
              const provinceFeature = this.codeData[this.value].mapData.features.find(
                (feature) => feature.properties.name === provinceName
              );

              if (provinceFeature && provinceFeature.properties.centroid) {
                const center = provinceFeature.properties.centroid;
                // 添加星星标记
                provincesWithStars.push({
                  name: provinceName,
                  value: [...center, item.preium || 0],
                  symbol: "circle",
                  symbolSize: 6,
                  itemStyle: {
                    color: {
                      type: "radial",
                      x: 0.3,
                      y: 0.3,
                      r: 0.3,
                      colorStops: [
                        { offset: 0, color: "#FFFFFF" },
                        { offset: 0.5, color: "#FFD700" },
                        { offset: 1, color: "#FFA500" },
                      ],
                    },
                  },
                });

                // 添加航线数据
                linesData.push({
                  fromName: "北京市",
                  toName: provinceName,
                  coords: [beijingCoord, center],
                });
              }
            }
          }
        }

        // 绘制图表
        var option = {
          title: {
            text: "全国电采暖设备分布",
            left: "center",
            textStyle: {
              color: "#ffffff",
              fontSize: 24,
            },
          },
          tooltip: {
            trigger: "item",
            showDelay: 0,
            transitionDuration: 0.2,
            borderColor: "rgba(255, 255, 255, 0.2)",
            backgroundColor: "rgba(0, 0, 0, 0.8)",
            borderWidth: 1,
            textStyle: {
              color: "#ffffff",
            },
            formatter: (params) => {
              // 检查数据是否存在
              if (params.data && params.data.preium !== undefined) {
                return `${params.name}<br/>保费: ${params.data.preium}<br/>目标: ${params.data.target}<br/>完成率: ${params.data.value}%`;
              }
              // 如果在totalMapData中能找到对应数据
              if (this.totalMapData && Array.isArray(this.totalMapData)) {
                const provinceData = this.totalMapData.find(
                  (item) => item && item.comname2 === params.name
                );
                if (provinceData) {
                  return `${params.name}<br/>保费: ${provinceData.preium}<br/>目标: ${provinceData.target}<br/>完成率: ${provinceData.achieveRate}%`;
                }
              }
              return params.name + ": 暂无项目";
            },
          },
          visualMap: {
            min: 0,
            max: 150,
            right: "30px",
            bottom: "20px",
            text: ["高", "低"],
            calculable: true,
            inRange: {
              color: ["#133a73", "#143a73", "#123a73"],
            },
            textStyle: {
              color: "#ffffff",
            },
          },
          geo: {
            show: true,
            type: "map",
            map: this.codeData[this.value].word, // 使用已注册的china地图显示南海诸岛迷你地图
            boundingCoords: [
              [80, 16], // 西南角坐标 (经度, 纬度)
              [136, 55], // 东北角坐标 (经度, 纬度)
            ],
            nameMap: {
              香港特别行政区: "香港",
              澳门特别行政区: "澳门",
            },
            label: {
              show: true,
              fontSize: 12,
              color: "#fff",
              offset: [0, 10], // 默认所有省份标签向下偏移10像素
              emphasis: {
                show: true,
                color: "#fff",
                fontSize: 14,
              },
            },
            regions: [
              {
                name: "河北省",
                label: {
                  offset: [-10, 25], // 向上偏移20像素，避免遮挡北京
                },
              },
              {
                name: "甘肃省",
                label: {
                  offset: [0, -15], // 向上偏移20像素，避免遮挡北京
                },
              },
              {
                name: "澳门",
                label: {
                  offset: [-10, 15], // 保持默认位置
                },
              },
              // 南海诸岛缩略图设置
              {
                name: "南海诸岛",
                itemStyle: {
                  areaColor: "#031f41",
                  borderColor: "#2c6097",
                  borderWidth: 1, // 设置边框为1像素
                },

                label: {
                  show: false, // 隐藏标签
                },
                emphasis: {
                  disabled: true, // 禁用高亮效果
                  itemStyle: {
                    areaColor: "#031f41",
                    borderColor: "#2c6097",
                    borderWidth: 1,
                  },
                },
                select: {
                  disabled: true, // 禁用选中效果
                  itemStyle: {
                    areaColor: "#031f41",
                    borderColor: "#2c6097",
                    borderWidth: 1,
                  },
                },
                tooltip: {
                  show: false,
                },
              },
            ],
            itemStyle: {
              areaColor: "#031f41",
              borderWidth: 2,
              borderColor: "#2c6097",
            },
            zoom: 1.2,
            emphasis: {
              label: {
                show: true,
                color: "#ffffff",
                fontSize: 14,
              },
              itemStyle: {
                areaColor: "#1e90ff",
                borderColor: "#8ab4e5",
                borderWidth: 2,
              },
            },
            select: {
              label: {
                show: true,
                color: "#ffffff",
                fontSize: 14,
              },
              itemStyle: {
                areaColor: "#143a73",
                borderColor: "#2c6097",
                borderWidth: 2,
                color: "#fff",
              },
            },
          },
          series: [
            {
              name: "完成率",
              type: "map",
              geoIndex: 0,
              data: mapData,
              // 添加点击事件处理
              selectedMode: "single",
              emphasis: {
                disabled: false,
              },
            },
            // 星星标记点
            {
              name: "省份标记",
              type: "effectScatter",
              coordinateSystem: "geo",
              data: provincesWithStars,
              tooltip: {
                borderColor: "rgba(255, 255, 255, 0.2)",
                backgroundColor: "rgba(0, 0, 0, 0.8)",
                borderWidth: 1,
                textStyle: {
                  color: "#ffffff",
                },
                formatter: (params) => {
                  if (this.totalMapData && Array.isArray(this.totalMapData)) {
                    const provinceData = this.totalMapData.find(
                      (item) =>
                        item &&
                        ((this.provinceNameMap && this.provinceNameMap[item.comname2]) ||
                          item.comname2) === params.name
                    );
                    if (provinceData) {
                      return `${params.name}<br/>保费: ${provinceData.preium}<br/>目标: ${provinceData.target}<br/>完成率: ${provinceData.achieveRate}%`;
                    }
                  }
                  return params.name;
                },
              },
              rippleEffect: {
                period: 2, //线动画周期，值越小越快
                scale: 4, //线动画大小
                brushType: "fill", //线动画类型'
                color: "rgba(255, 215, 0, 0.8)", // 带透明度的颜色
              },
            },
            // 航线连接
            {
              name: "航线",
              type: "lines",
              coordinateSystem: "geo",
              zlevel: 2,
              effect: {
                show: true,
                period: 6,
                trailLength: 0.7,
                color: "#fff",
                symbolSize: 3,
              },
              lineStyle: {
                color: "#FFD700",
                width: 0,
                curveness: 0.2,
              },
              data: linesData,
              silent: true,
            },
            // 保留散点图
            {
              type: "scatter",
              coordinateSystem: "geo",
              rippleEffect: {
                period: 2,
                brushType: "stroke",
                scale: 1,
              },
              label: {
                normal: {
                  show: true,
                  position: "top",
                },
              },
              itemStyle: {
                color: "#fc5531",
              },
              symbol: "circle",
              symbolSize: function (value) {
                return value && value[2] ? value[2] : 10;
              },
              data: [],
            },
          ],
        };

        // 监听地图点击事件
        this.chinaChart.on("click", (params) => {
          if (params.name === "南海诸岛") return;
          if (params.componentType === "series" && params.seriesType === "map") {
            // 使用nextTick确保在DOM更新后再处理点击事件
            this.$nextTick(() => {
              // 处理省份点击事件
              this.handleProvinceClick(params.name);
            });
          }
        });

        this.chinaChart.setOption(option);
      }
    },

    toggleFullscreen() {
      if (!this.isFullscreen) {
        // 进入全屏
        this.enterFullscreen();
      } else {
        // 退出全屏
        this.exitFullscreen();
      }
    },
    enterFullscreen() {
      const element = this.$el; // 只全屏当前组件

      if (element.requestFullscreen) {
        element.requestFullscreen();
      } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
      } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
      } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
      }

      this.isFullscreen = true;
    },

    exitFullscreen() {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }

      this.isFullscreen = false;
      // this.$nextTick(() => {
      //   setTimeout(() => {
      //     this.resizeCharts();
      //   }, 100);
      // });
    },
    handleFullscreenChange() {
      // 检查当前是否处于全屏状态
      const isCurrentlyFullscreen =
        document.fullscreenElement ||
        document.webkitFullscreenElement ||
        document.mozFullScreenElement ||
        document.msFullscreenElement;

      this.isFullscreen = !!isCurrentlyFullscreen;

      // 在下一个事件循环中调整地图大小
      this.$nextTick(() => {
        setTimeout(() => {
          this.resizeCharts();
        }, 100);
      });
    },
    // 在窗口大小改变时也调整地图大小
    handleWindowResize() {
      this.resizeCharts();
    },
    returnToChina() {
      this.currentLevel = "country";
    },
    resizeCharts() {
      // 调整全国地图大小（仅当元素可见时）
      if (this.chinaChart && this.currentLevel === "country") {
        this.chinaChart.resize();
      }

      // 调整省份地图大小（仅当元素可见时）
      if (this.provinceChart && this.currentLevel === "province") {
        this.provinceChart.resize();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
/* 样式保持不变 */
.container {
  width: 100%;
  height: calc(100vh - 50px);
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-direction: row;
  flex-wrap: wrap;
  background: linear-gradient(135deg, #0a1a2f 0%, #1a1a2f 100%);
  position: relative;

  // 全屏时的样式
  &.fullscreen {
    height: 100vh !important;
    width: 100vw !important;
  }
}

#chinaMap,
#provinceMap {
  width: 100%;
  height: 100%;
}

.china {
  width: 100%;
  // width: calc(100% - 200px);
  height: calc(100% - 20px);
  margin-top: 20px;
  position: relative;
  // 全屏时的样式
  .container.fullscreen & {
    height: 100%;
    margin-top: 20px;
  }
}

.return-button {
  position: absolute;
  top: 20px;
  right: 80px;
  z-index: 99;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;

  &:hover {
    background: rgba(0, 0, 0, 0.9);
  }
}

.statistics-wrapper {
  position: absolute;
  left: 30px;
  top: 30px;
  background: rgba(255, 255, 255, 0.1);
  padding: 15px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 0 15px rgba(0, 255, 255, 0.2);
  color: #fff;
  font-size: 0.9em;
  h3 {
    font-size: 1.1em;
    color: #00ffff;
    margin-top: 0;
    margin-bottom: 10px;
  }
  p {
    margin-bottom: 5px;
  }
  span {
    font-size: 1.2rem;
    padding-left: 5px;
    font-weight: bold;
    color: #ffeb3b;
  }
}
.full-screen {
  position: absolute;
  top: 20px;
  right: 25px;
  color: #fff;
  padding: 8px 15px;
  background: rgba(0, 0, 0, 0.7);
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  z-index: 100;
}
</style>
